/*
 * @Auther        : SR
 * @Date          : 2022-02-25 16:16:48
 * @LastEditTime  : 2022-02-28 15:55:37
 */
package windows

import (
	"fmt"
	"ipfs-browser/src/Metadata"
	"ipfs-browser/src/es7"
	"log"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
)

func showResult(filesInfo *widget.Accordion, res []Metadata.Metadata) {
	filesInfo.Items = nil
	for _, item := range res {
		timeUnix := item.Timestamp.Unix()
		formatTimeStr := time.Unix(timeUnix, 0).Format("2006-01-02 15:04:05")
		filesInfo.Append(
			&widget.AccordionItem{
				Title: item.Name,
				Detail: container.NewBorder(
					container.NewAdaptiveGrid(
						3,
						container.NewBorder(
							widget.NewSeparator(),
							widget.NewSeparator(),
							widget.NewSeparator(),
							widget.NewSeparator(),
							widget.NewLabel(item.CID),
						),
						widget.NewLabel(item.Filetype),
						widget.NewLabel(formatTimeStr),
					),
					nil, nil, nil,
					&widget.Entry{
						Text:      item.Description,
						Wrapping:  fyne.TextWrapWord,
						MultiLine: true,
					},
				),
			},
		)
	}

}

// dialogScreen loads demos of the dialogs we support
func searchScreen(win fyne.Window) fyne.CanvasObject {
	filesInfo := widget.NewAccordion() //搜索栏下方的显示信息

	selectBar := widget.NewSelect([]string{"all", "text", "picture", "video"}, func(s string) { fmt.Println("selected", s) })

	inputKeyword := widget.NewEntry()
	inputKeyword.SetText("input keyword")
	inputKeyword.Wrapping = fyne.TextWrapOff

	searchButton := widget.NewButton("Search", func() {
		log.Println("search files by keyword : "+inputKeyword.Text, "type :", selectBar.Selected)
		res, err := es7.Query(selectBar.Selected, inputKeyword.Text)
		if err != nil {
			log.Println("search error:", err)
		} else {
			// show search result
			showResult(filesInfo, res)
		}

	})

	return container.NewBorder(
		container.NewBorder(
			nil,
			widget.NewSeparator(),
			inputKeyword,
			container.NewHBox(selectBar, searchButton),
		),
		nil, nil, nil,
		// widget.NewSeparator(),
		container.NewVScroll(filesInfo),
	)
}
